'use strict';

exports.__esModule = true;
exports.extendDomPrototpe = extendDomPrototpe;
exports.addStyle = addStyle;
exports.addLink = addLink;
exports.getNaturalSize = getNaturalSize;
exports.createElementByHTML = createElementByHTML;
exports.polyfill = polyfill;
function createElement(content) {
    var wrap = document.createElement('DIV');
    wrap.innerHTML = content;
    if (!wrap.firstElementChild) throw new TypeError('after \'' + content + '\' is an illegal html tag string.');
    return wrap.firstElementChild;
}

var scopeStyles = exports.scopeStyles = {};

var elementPrototype = exports.elementPrototype = typeof HTMLElement !== "undefined" ? HTMLElement.prototype : Element.prototype;

var auiFindSelectorAll = function auiFindSelectorAll(selector) {
    if (!this || this === null) {
        return;
    }
    if (/(^\s*|,\s*)>/.test(selector)) {
        if (!this.id) {
            this.id = 'ID_' + new Date().getTime();
            var removeId = true;
        }
        selector = selector.replace(/(^\s*|,\s*)>/g, '$1#' + this.id + ' >');
        var result = document.querySelectorAll(selector);
        if (removeId) {
            this.id = null;
        }
        return result;
    } else {
        return this.querySelectorAll(selector);
    }
};

var auiFindSelector = function auiFindSelector(selector) {
    var res = this.auiFindSelectorAll(selector);
    if (res.length < 1) {
        return null;
    }
    return res[0];
};

var auiToggleAttribute = function auiToggleAttribute(key, value) {
    if (this.hasAttribute(key)) {
        this.removeAttribute(key);
        return false;
    } else {
        this.setAttribute(key, value);
        return true;
    }
};

var auiHasClass = function auiHasClass(name) {
    if (this.classList) {
        return this.classList.contains(name);
    } else {
        return this.className.indexOf(name) > -1;
    }
};

var auiAddOnceClass = function auiAddOnceClass(name) {
    if (this.classList) {
        if (!this.classList.contains(name)) {
            this.classList.add(name);
        }
    }
};

var auiRemoveOnceClass = function auiRemoveOnceClass(name) {
    if (this.classList) {
        if (this.classList.contains(name)) {
            this.classList.remove(name);
        }
    }
};

var auiGetAttribute = function auiGetAttribute(name, defaultval) {
    var ret = this.getAttribute(name);
    if (ret === null) {
        if (defaultval) {
            return defaultval;
        }
        return null;
    }
    return ret;
};

var auiHeight = function auiHeight() {
    return getComputedStyle(this).height;
};

var auiWidth = function auiWidth() {
    return getComputedStyle(this).width;
};

/**
 * Removes an event listener from an element.
 */
var auiOff = exports.auiOff = function auiOff(evt, fn) {
    var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

    this.removeEventListener(evt, fn, opts);
};

/**
 * Adds an event listener to an element with the ability to use event delegation.
 */
var auiOn = exports.auiOn = function auiOn(evt, fn) {
    var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

    var delegatorFn = function delegatorFn(e) {
        return e.target.matches(opts.target) && fn.call(e.target, e);
    };
    this.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
    if (opts.target) return delegatorFn;
};

function extendDomPrototpe(key, func) {
    var doc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window.document;

    doc[key] = func;
    elementPrototype[key] = func;
}

var getIEVersion = exports.getIEVersion = function getIEVersion() {
    if (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) {
        return parseFloat(RegExp.$1);
    } else {
        return -1;
    }
};

/**
 * 添加一个style
 *
 * @param key
 * @param css
 * @param once
 */
function addStyle(key, css) {
    var once = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

    if (!scopeStyles[key] && once) {
        var head = document.head || document.getElementsByTagName('head')[0];
        var style = document.createElement('style');
        var id = "scopedcss_" + key;

        style.id = id;
        style.type = 'text/css';
        if (style.styleSheet) {
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }

        scopeStyles[key] = style;
        head.appendChild(style);
    }
}

/**
 * 添加一个link
 *
 * @param href
 * @param rel
 */
function addLink(href) {
    var rel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "stylesheet";

    var head = document.head || document.getElementsByTagName('head')[0];
    var link = document.createElement("link");
    link.rel = rel;
    link.href = href;
    head.appendChild(link);
}

var global_hack_img = new Image();
/**
 * 获得图片原始大小
 * 
 * @param {*} img 
 */
function getNaturalSize(img) {
    var naturalSize = {};
    if (img.naturalWidth && img.naturalHeight) {
        naturalSize.width = img.naturalWidth;
        naturalSize.height = img.naturalHeight;
    } else {
        global_hack_img.src = img.src;
        naturalSize.width = global_hack_img.width;
        naturalSize.height = global_hack_img.height;
    }
    return naturalSize;
}

/** 
* Creates an element from a string 
*/
function createElementByHTML() {
    var el = document.createElement('div');
    el.innerHTML = str;
    return el.firstElementChild;
}

/**
 * Returns true if the element specified is visible in the viewport, false otherwise.
 * 
 * @param {*} el 
 * @param {*} partiallyVisible 
 */
var elementIsVisibleInViewport = exports.elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {
    var partiallyVisible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    var _el$getBoundingClient = el.getBoundingClientRect(),
        top = _el$getBoundingClient.top,
        left = _el$getBoundingClient.left,
        bottom = _el$getBoundingClient.bottom,
        right = _el$getBoundingClient.right;

    var _window = window,
        innerHeight = _window.innerHeight,
        innerWidth = _window.innerWidth;

    return partiallyVisible ? (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

/**
 * Returns the scroll position of the current page.
 */
var getScrollPosition = exports.getScrollPosition = function getScrollPosition() {
    var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
    return {
        x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
        y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
    };
};

/**
 * Creates a hash for a value using the SHA-256 algorithm. Returns a promise.
 */
var hashBrowser = exports.hashBrowser = function hashBrowser(val) {
    return crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(function (h) {
        var hexes = [],
            view = new DataView(h);
        for (var i = 0; i < view.byteLength; i += 4) {
            hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
        }return hexes.join('');
    });
};

/**
 * Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.
 */
var observeMutations = exports.observeMutations = function observeMutations(element, callback, options) {
    var observer = new MutationObserver(function (mutations) {
        return mutations.forEach(function (m) {
            return callback(m);
        });
    });
    observer.observe(element, Object.assign({
        childList: true,
        attributes: true,
        attributeOldValue: true,
        characterData: true,
        characterDataOldValue: true,
        subtree: true
    }, options));
    return observer;
};

var onUserInputChange = exports.onUserInputChange = function onUserInputChange(callback) {
    var type = 'mouse',
        lastTime = 0;
    var mousemoveHandler = function mousemoveHandler() {
        var now = performance.now();
        if (now - lastTime < 20) type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler);
        lastTime = now;
    };
    document.addEventListener('touchstart', function () {
        if (type === 'touch') return;
        type = 'touch', callback(type), document.addEventListener('mousemove', mousemoveHandler);
    });
};

var runAsync = exports.runAsync = function runAsync(fn) {
    var worker = new Worker(URL.createObjectURL(new Blob(['postMessage((' + fn + ')());']), {
        type: 'application/javascript; charset=utf-8'
    }));
    return new Promise(function (res, rej) {
        worker.onmessage = function (_ref) {
            var data = _ref.data;

            res(data), worker.terminate();
        };
        worker.onerror = function (err) {
            rej(err), worker.terminate();
        };
    });
};

var scrollToTop = exports.scrollToTop = function scrollToTop() {
    var c = document.documentElement.scrollTop || document.body.scrollTop;
    if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8);
    }
};

var UUIDGeneratorBrowser = exports.UUIDGeneratorBrowser = function UUIDGeneratorBrowser() {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) {
        return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
    });
};

function polyfillShear() {

    /**
     * 多行折断 
     * 
     * @param target 
     * @param line_count 
     * @param after_html 
     * 
     * @example 
     *  document.auiShear(document.getElementById('target'), 3);
     *  document.auishear(document.getElementById('target'),  3, '<span>（展开）</span>');
     */
    document.auiShear = function (target) {
        var line_count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        var after_html = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

        var sel = window.getSelection();

        var full_html = target.innerHTML;
        var full_text = target.textContent;

        sel.selectAllChildren(target);
        sel.collapseToStart();

        for (var i = 0; i < line_count; i++) {
            sel.modify('extend', 'right', 'character');
            sel.modify('extend', 'right', 'lineboundary');
            if (!target.contains(sel.getRangeAt(0).endContainer)) {
                sel.selectAllChildren(target);
                break;
            }
        }

        var cut_node = sel.getRangeAt(0).cloneContents();
        var wrap = document.createElement('DIV');
        wrap.appendChild(cut_node);
        var cut_html = wrap.innerHTML;
        var cut_text = cut_node.textContent;

        target.innerHTML = cut_html;

        sel.selectAllChildren(target);
        sel.collapseToEnd();

        var cut_html_with_after_html = '';
        var cut_text_with_after_html = '';
        var br = createElement('<br/>');
        if (after_html !== '') {
            var insert = createElement(after_html);
            target.appendChild(br);
            target.appendChild(insert);
            var rect = insert.getBoundingClientRect();
            for (var _i = 0; _i < 1000; _i++) {
                sel.modify('extend', 'left', 'character');
                if (sel.getRangeAt(0).getBoundingClientRect().width >= rect.width) {
                    sel.deleteFromDocument();
                    break;
                }
            }
            target.removeChild(br);
            cut_html_with_after_html = target.innerHTML;
            cut_text_with_after_html = target.textContent;
        }

        return {
            full_html: full_html,
            full_text: full_text,
            cut_html: cut_html,
            cut_text: cut_text,
            cut_html_with_after_html: cut_html_with_after_html,
            cut_text_with_after_html: cut_text_with_after_html
        };
    };
}

function polyfillDom(doc) {
    var _div = doc.createElement("div");
    doc.auiCreateDOM = function (html, attrs) {
        _div.innerHTML = html;
        var dom = _div.children[0];
        for (var key in attrs) {
            dom.setAttribute(key, attrs[key]);
        }
        return dom;
    };
}

function polyfill() {
    var doc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.document;

    extendDomPrototpe("auiFindSelectorAll", auiFindSelectorAll, doc);
    extendDomPrototpe("auiFindSelector", auiFindSelector, doc);
    extendDomPrototpe("auiToggleAttribute", auiToggleAttribute, doc);
    extendDomPrototpe("auiHasClass", auiHasClass, doc);
    extendDomPrototpe("auiAddOnceClass", auiAddOnceClass, doc);
    extendDomPrototpe("auiRemoveOnceClass", auiRemoveOnceClass, doc);
    extendDomPrototpe("auiGetAttribute", auiGetAttribute, doc);
    extendDomPrototpe("auiWidth", auiWidth, doc);
    extendDomPrototpe("auiHeight", auiHeight, doc);
    extendDomPrototpe("auiOn", auiOn, doc);
    extendDomPrototpe("auiOff", auiOff, doc);
    doc.auiIeVersion = getIEVersion();
    polyfillDom(doc);
}